<script setup lang="ts">
import { useTheme } from "@/composables/useTheme";
import { LOGIN_STATUS, LOGIN_BUSIN_STATUS, USER_INFO } from "@/config/cache.js";
import Cache from "@/utils/cache";
import { toLogin } from "@/libs/login.js";
import {
  getUserInfo,
  getCurlOauth,
  getOpenidByCode,
  getWechatFollow,
} from "@/api/user";
import { useTokenStore } from "@/store/index";
import saveUserInfoToLocation from "@/composables/saveUserInfoToLocation";
import { isWeixin, Tips } from "@/utils/index";
import { getBaseUrl } from "@/utils/env";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { getWechatShare } from "@/api/public";
import {
  marketGet,
  getPolicyList,
  getReminderList,
  getSave,
  remove,
} from "@/api/home";
onShow(() => {});
const baseURL = getBaseUrl();
const { colorStyle } = useTheme();

onLoad((option) => {
  // 判断是否有分享缓存，没有的话删除
  if (option.urltype) {
    Cache.set("urltype", option.urltype);
    Cache.set("business_id", option.business_id);
  } else {
    Cache.clear("urltype", option.urltype);
    Cache.clear("business_id", option.business_id);
  }
  // 分享进来的需要公众号授权
  if (isWeixin()) {
    const token = uni.getStorageSync(LOGIN_STATUS);
    // 微信浏览器环境需授权登录，token用于首页到价提醒功能操作
    if (option.reflesh) {
      getCurlOauthHandler();
    } else {
      setTokenHandler();
    }

    return;
  }
  goHome();
});

// 获取公众号授权链接并跳转
async function getCurlOauthHandler() {
  let { data } = await getWechatShare();
  let home_url = data.home_url;
  let redirect_url = `${home_url || "https://bjp.yjgold.cn"}/pages/index/index`;
  if (Cache.get("business_id")) {
    redirect_url += `?business_id=${Cache.get("business_id")}`;
  }
  if (Cache.get("urltype")) {
    redirect_url += `&urltype=${Cache.get("urltype")}`;
  }
  let params = { mode: 0, source: redirect_url };
  let res = await getCurlOauth(params);
  let { auth_url } = res.data;
  window.location = auth_url;
}
// 存储token
async function setTokenHandler() {
  const token = uni.getStorageSync(LOGIN_STATUS);
  const businessToken = uni.getStorageSync(LOGIN_BUSIN_STATUS);

  // #ifdef H5
  var url = window.location.href;
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(url.indexOf("?") + 1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }

  if (theRequest.code && !token) {
    // 存在code时，调用接口获取token
    // 使用code和state调用接口获取普通用户的token
    console.log("theRequest", theRequest);
    let res = await getOpenidByCode({
      code: theRequest.code,
      state: theRequest.state,
    });
    let { data, code, info } = res;
    let token = data.token.token;
    const tokenStore = useTokenStore();
    await tokenStore.setToken(token);
    if (code != 1)
      return Tips({
        title: info,
      });
    // 不是通过分享进入的，判断是否存在busin_token：不存在跳转登录页;存在获取用户信息并跳转首页
    if (!Cache.get("business_id")) {
      if (!Cache.get(LOGIN_BUSIN_STATUS)) {
        toLogin();
      } else {
        getUserInfoHandler();
      }
    } else {
      // 分享进来授权公众号后直接跳转首页
      goHome();
    }

    return;
  }
  if (!theRequest.code && !token) {
    getCurlOauthHandler();
    return;
  }
  // 存在token时获取用户信息判断是否授权微信公众token
  if (token) {
    try {
      getWechatFollow();
    } catch (error) {}
    // 分享进入的
    if (Cache.get("business_id")) {
      setTimeout(() => {
        goHome();
      }, 1000);
    } else {
      // 企业用户登录进来的判断是否有bustoken
      if (businessToken) {
        getUserInfoHandler();
      } else {
        toLogin();
      }
    }
  }

  // #endif
}
function getUserInfoHandler() {
  // 缓存用户信息
  getUserInfo()
    .then((res: any) => {
      saveUserInfoToLocation(res.data.business);
      goHome();
    })
    .catch((err) => {});
}
function goHome() {
  let homeUrl = "/pages/tabbar/home";
  if (Cache.get("business_id")) {
    homeUrl += `?business_id=${Cache.get("business_id")}`;
  }
  if (Cache.get("urltype")) {
    homeUrl += `&urltype=${Cache.get("urltype")}`;
  }
  uni.switchTab({
    url: homeUrl,
    fail(err) {
      uni.redirectTo({
        url: homeUrl,
      });
    },
  });
}
</script>
<template>
  <view class="wrap flex_fc" :style="colorStyle">
    <image class="img_box" src="@/static/image/index.png" mode="scaleToFill" />
    <text>贵金属智能管理平台</text>
  </view>
</template>

<style scoped lang="scss">
.wrap {
  width: 100vw;
  height: 100vh;
  image {
    display: block;
    width: 350rpx;
    height: 350rpx;
    margin-bottom: 30rpx;
  }
  text {
    text-align: center;
    font-size: 40rpx;
    font-weight: bold;
    background: linear-gradient(
      to right,
      #ac8e6c,
      #6d3d13
    ); /*设置渐变的方向从左到右 颜色从ff0000到ffff00*/
    -webkit-background-clip: text; /*将设置的背景颜色限制在文字中*/
    -webkit-text-fill-color: transparent; /*给文字设置成透明*/
  }
}
</style>
